package com.wb.config.AjaxSecurity;

import com.wb.service.UserDetailServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCrypt;

import javax.annotation.Resource;

/**
 * 自定义账号密码验证
 */
@Configuration
public class SelfAuthenticationProvider implements AuthenticationProvider {

    private final Logger logger = LoggerFactory.getLogger(SelfAuthenticationProvider.class);

    @Resource(name = "userDetailServiceImpl")
    UserDetailServiceImpl userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String userName = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();

        UserDetails userInfo = userDetailsService.loadUserByUsername(userName);
        boolean checkpw = true;
        try {
            checkpw = BCrypt.checkpw(password, userInfo.getPassword());
        } catch (Exception e) {
            logger.error(" password :  "  + password + "userInfo.password : " + userInfo.getPassword(), e);
        }
//        boolean checkpw = bCryptPasswordEncoder.matches(password , userInfo.getPassword());
        if (!checkpw) {
            throw new BadCredentialsException("用户名密码不正确，请重新登陆！");
        }
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userInfo, password, userInfo.getAuthorities());
        logger.info(" ---------------------- authenticationToken : {} " , authenticationToken);
        return authenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}
